package com.xieh.webmagic.magic;


import com.xieh.webmagic.dao.UserDao;
import com.xieh.webmagic.entity.UserEntity;
import com.xieh.webmagic.magic.util.DownloadUtil;
import com.xieh.webmagic.magic.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.io.IOException;

/**
 * @author 谢辉
 * @Classname UserPipeline
 * @Description TODO
 * @Date 2020/11/20 16:33
 */
@Component
public class UserPipeline implements Pipeline {
    @Autowired
    private IdWorker idWorker;

    @Autowired
    private UserDao userDao;


    @Override
    public void process(ResultItems resultItems, Task task) {
        String nickName = resultItems.get("nickName");
        String image = resultItems.get("image");
        String imageName = image.substring(image.lastIndexOf("/") + 1) + ".jpg";

        UserEntity user = new UserEntity();
        user.setId(idWorker.nextId()+"");
        user.setImg(imageName);
        user.setNickName(nickName);
        // 将用户存入数据库
        userDao.insert(user);

        // 将图片下载下载
        try {
            DownloadUtil.download(image,imageName,"E:/tensquare/userimage");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
